import { Component, ElementRef, Renderer, Output, EventEmitter, OnInit } from '@angular/core';
import config from '../../../common/utils/baseUrl';
import getData_ajax from '../../../common/utils/getData_ajax';
import {
  AbstractControl,
  FormBuilder,
  FormControl,
  FormGroup,
  Validators,
} from '@angular/forms';
import * as addDays from 'date-fns/add_days';
import * as getISOWeek from 'date-fns/get_iso_week';
import { registerLocaleData } from '@angular/common';
import zh from '@angular/common/locales/zh';

registerLocaleData(zh);
import * as $ from 'jquery';
import * as wangEditor from '../../../../../node_modules/wangeditor/release/wangEditor.js';
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
import { DatePipe } from '@angular/common';
import { NzModalService } from 'ng-zorro-antd';
import promise from '../../../common/utils/promise';

@Component({
  selector: 'app-edit-article',
  templateUrl: './edit-article.component.html',
  styleUrls: ['./edit-article.component.scss'],
})
export class EditArticleComponent implements OnInit {
  validateForm: FormGroup;

  public isSpinning: any = true; // 加载状态
  public ariticeData: any = []; // 文章数据
  public date: any = null; // 初始化日期
  public sendImgdata: any = {}; // 上传的图片数据
  public sendData: any = {
    title: '',
    img: '',
    date: '',
    details: '',
    aritice_introduction: '',
    id: 0, // 0 为新增，其他为修改
  }; // 上传到接口数据
  private editor: any;
  public queryParams: any = {}; // url参数地址
  @Output() onPostData = new EventEmitter();

  constructor(private fb: FormBuilder, private el: ElementRef, private renderer: Renderer,
              private activatedRoute: ActivatedRoute, private datePipe: DatePipe, private modalService: NzModalService,
              private router: Router) {
  }


  ngOnInit() {
    // 调回本页面，刷新页面
    this.router.events.subscribe((item) => {
      if (item instanceof NavigationEnd && item.url.indexOf('/article-management/edit-article') > -1 && this.activatedRoute.snapshot.queryParams.reload) {
        this.getData();
      }
    });
    this.activatedRoute.queryParams.subscribe(params => {
      this.queryParams = params;
    });
    this.validateForm = this.fb.group({
      title: [null, [Validators.required]],
      date: [null, [Validators.required]],
      show_img: [null],
      introduce: [null, [Validators.required]],
    });
    this.getData();
  }


  // 配置wangeditor
  ngAfterViewInit() {
    let editordom = this.el.nativeElement.querySelector('#editorElem');
    // 配置服务器端地址
    this.editor = new wangEditor(editordom);
    // 配置editor图片上传路径
    this.editor.customConfig.uploadImgServer = config.uploadImgUrl + '/api/inputService/uploadImg';
    // 配置editor图片上传文件名
    this.editor.customConfig.uploadFileName = 'myfile';
    this.editor.customConfig.uploadImgShowBase64 = true;
    this.editor.create();
  }

  clickHandle(): any {
    let data = this.editor.txt.text();//只有wangeditor的文字
    // let data = this.editor.txt.html();//只有wangeditor的包含标签的内容
    return data;
  }

  // 日期改变时间
  changeDate(result: Date): void {
    console.log('onChange: ', result);
  }


  confirmationValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (control.value !== this.validateForm.controls.password.value) {
      return { confirm: true, error: true };
    }
  };

  getCaptcha(e: MouseEvent): void {
    e.preventDefault();
  }

  // 拉取数据
  getData() {
    let that = this;
    if (that.queryParams.id == 0 || that.queryParams.id == undefined) { // 新增
      that.sendData.id = that.queryParams.id;
      that.isSpinning = false;
      this.sendData.img = '';
      that.validateForm.reset();
    } else {  // 修改
      // getData_ajax.getFunc(config.baseUrl + '/api/articleService/getArticeData', 'post', this.queryParams, function(data) {
      //     that.ariticeData = data;
      //     that.isSpinning = false;
      //     that.sendData.id = that.queryParams.id;
      //     // 为form表单赋值
      //     that.validateForm.patchValue({
      //       title: that.ariticeData.result[0].title,
      //       date: that.ariticeData.result[0].date,
      //       introduce: that.ariticeData.result[0].details,
      //     });
      //     that.sendData.img = that.ariticeData.result[0].img;
      //     that.editor.txt.html(that.ariticeData.result[0].aritice_introduction);
      //     console.log(that.ariticeData);
      //   },
      //   function(error) {
      //     console.log(error);
      //   });
      promise.commonRequest.post(this.queryParams, '/api/articleService/getArticeData').then((data) => {
        // @ts-ignore
        if (data.isEffective) {
          // @ts-ignore
          that.ariticeData = data;
          that.isSpinning = false;
          that.sendData.id = that.queryParams.id;
          // 为form表单赋值
          that.validateForm.patchValue({
            title: that.ariticeData.result[0].title,
            date: that.ariticeData.result[0].date,
            introduce: that.ariticeData.result[0].details,
          });
          that.sendData.img = that.ariticeData.result[0].img;
          that.editor.txt.html(that.ariticeData.result[0].aritice_introduction);
          console.log(that.ariticeData);
        } else {
          this.router.navigateByUrl('/passport/login');
          sessionStorage.setItem('previousUrl', window.location.pathname);
        }
      }).catch(error => {
        if (!error.responseJSON.isEffective) {
          this.router.navigateByUrl('/passport/login');
          sessionStorage.setItem('previousUrl', window.location.pathname);
        }
      });
    }
  }

  // 提交表单
  submitForm(): void {
    let that = this;
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    // 组合数据
    this.sendData.title = this.validateForm.value.title;
    this.sendData.date = this.datePipe.transform(new Date(this.validateForm.value.date), 'yyyy-MM-dd HH:mm:ss');
    this.sendData.details = this.validateForm.value.introduce;
    this.sendData.aritice_introduction = this.editor.txt.html();
    // 请求接口
    promise.commonRequest.post(this.sendData, '/api/saveService/saveArticle').then(data => {
      // @ts-ignore
      if (data.isEffective) {
        // @ts-ignore
        this.modalService.success({
          nzTitle: '成功',
          nzContent: '点击返回上一页',
          nzOnOk: () => {
            this.router.navigate(['/article-management/article-list'], { queryParams: { reload: true } });
            // that.router.navigateByUrl('/article-management/article-list');
          },
        });
      } else {
        this.router.navigateByUrl('/passport/login');
        sessionStorage.setItem('previousUrl', window.location.pathname);
      }
    }).catch(error => {
      if (!error.responseJSON.isEffective) {
        this.router.navigateByUrl('/passport/login');
        sessionStorage.setItem('previousUrl', window.location.pathname);
      } else {
        this.modalService.success({
          nzTitle: '失败',
          nzContent: '失败，请稍后重试...',
        });
        console.log(error);
      }
    });
  }

  // 图片上传
  uploadImg() {
    return $('#show_img').click();
  }

  // 图片input改变事件
  imgChange() {
    // //传标题图片到后台处理
    let titleImg = $('#show_img')[0]; //因为得到的是一个jquery类型，所以需要转化为js类型
    let titleImgFile = titleImg.files;  //获取上一步获取的titlefile对象里面的files属性名
    for (let i = 0; i < titleImgFile.length; i++) {
      this.sendImg(titleImgFile[i]);  //执行上面的titleImgFile
    }
  }

  sendImg(file) {
    let that = this;
    this.sendImgdata = new FormData();  //动态创建form表单的一个ectype属性
    this.sendImgdata.append('myfile', file);
    getData_ajax.uploadImg(config.uploadImgUrl + '/api/inputService/uploadImg', that.sendImgdata, function(data) {
        console.log(data);
        that.sendData.img = data.data[0];
      },
      function(error) {
        console.log(error);
      });
  }
}
